﻿using ByHand.Model;
using ByHand.Services.Code;
using ByHand.Services.Interfaces;
using jQuery_File_Upload.MVC3.Upload;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BackEnd.Controllers
{
    public class ProductController : Controller
    {
        private readonly IProductService _ProductService;
        private readonly IProductOptionService _ProductOptionService;
        private readonly IProviderService _ProviderService;
        public ProductController(IProductService ProductService, IProviderService ProviderService, IProductOptionService ProductOptionService)
        {
            _ProductService = ProductService;
            _ProviderService = ProviderService;
            _ProductOptionService = ProductOptionService;
        }

        public ActionResult Index(string page, string filter)
        {
            if (string.IsNullOrWhiteSpace(page))
            {
                page = "1";
            }
            ViewData["tableindex"] = new { page = page, pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage), filter = filter };
            return View();
        }

        public ActionResult TableProduct(int page, int pagesize, string filter)
        {
            int total = 0;
            pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage);
            if (page == 0)
            {
                page = 1;
            }
            var model = new List<Product>();
            if (!string.IsNullOrWhiteSpace(filter))
            {
                model = _ProductService.GetByPageFilter(page, pagesize, out total, filter);
                ViewData["filter"] = filter;
            }
            else
            {
                model = _ProductService.GetByPage(page, pagesize, out total);
            }
            if ((total % pagesize) > 0)
            {
                ViewData["total"] = (total / pagesize) + 1;
            }
            else
            {
                ViewData["total"] = total / pagesize;
            }

            ViewData["curpage"] = page;
            ViewData["nextpage"] = page + 1;
            ViewData["prepage"] = page - 1;
            foreach (var item in model)
            {
                item.Provider = _ProviderService.GetById(item.ProviderID);
            }
            return PartialView(model);
        }

        public ActionResult Create()
        {
            var model = new Product();
            var date = DateTime.Now;
            model.EndDate = new DateTime(date.Year, date.Month, date.Day + 1, date.Hour, date.Minute, 0);
            ViewData["providers"] = _ProviderService.GetAllAvaiable();
            return View("form", model);
        }

        public ActionResult Edit(int id)
        {
            var model = _ProductService.GetById(id);
            ViewData["providers"] = _ProviderService.GetAllAvaiable();
            return View("form", model);
        }

        [ValidateInput(false)]
        public ActionResult Save()
        {
            var id = Convert.ToInt32(Request.Form["id"]);
            var name = Request.Form["name"];
            var provider = Request.Form["provider"];
            var price = Request.Form["price"];
            var baseprice = Request.Form["baseprice"];
            var quantity = Request.Form["quantity"];
            var enddate = Request.Form["enddate"];
            var des = Request.Form["des"];
            var intro = Request.Form["introduction"];
            var model = _ProductService.GetById(id);
            if (model == null)
            {
                model = new Product();
                model.ID = id;
            }
            model.Title = name;
            model.ProviderID = Convert.ToInt32(provider);
            model.Price = Convert.ToInt32(price);
            model.BasePrice = Convert.ToInt32(baseprice);
            model.Quantity = Convert.ToInt32(quantity);
            model.EndDate = Convert.ToDateTime(enddate);
            model.Description = des;
            model.Introduction = intro;
            model.CreatedDate = DateTime.Now;
            model.ModifiedDate = DateTime.Now;
            if (id == 0)
            {
                _ProductService.Add(model);
                model.ProductCode = Utility.GenerateProductCode(_ProviderService.GetById(model.ProviderID).ProviderCode, model.ID);
                _ProductService.Update(model);
                model = new Product();
            }
            else
            {
                //model.ImagePath = GetAllImagesName(model.ID);
                _ProductService.Update(model);
            }
            ViewBag.Result = "Success";
            ViewData["providers"] = _ProviderService.GetAllAvaiable();
            return View("form", model);
        }

        public ActionResult Del(int id)
        {
            var model = _ProductService.GetById(id);
            if (model != null)
            {
                model.IsDeleted = true;
                model.ModifiedDate = DateTime.Now;
                _ProductService.Update(model);
            }
            return Json(true);
        }

        public ActionResult UnDel(int id)
        {
            var model = _ProductService.GetById(id);
            if (model != null)
            {
                model.IsDeleted = false;
                model.ModifiedDate = DateTime.Now;
                _ProductService.Update(model);
            }
            return Json(true);
        }

        private string GetAllImagesName(int id)
        {
            var files =
                new DirectoryInfo(UploadHandler.GetStorage(id))
                    .GetFiles("*", SearchOption.TopDirectoryOnly)
                    .Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden))
                    .Select(f => f.Name)
                    .ToList();
            string output = "";
            for (int i = 0; i < files.Count; i++)
            {
                output += files[i] + ";";
            }
            return output;
        }

        public ActionResult Details(int id)
        {
            var model = _ProductService.GetById(id);
            return View(model);
        }
        public ActionResult Active(int id)
        {
            var p = _ProductService.GetActive();
            if (p != null)
            {
                p.IsActive = false;
                _ProductService.Update(p);
            }
            var p2 = _ProductService.GetById(id);
            p2.IsActive = true;
            _ProductService.Update(p2);
            return Json(true);
        }
        public ActionResult Option(int id)
        {
            var p = _ProductService.GetById(id);
            ViewData["productOption"] = _ProductOptionService.GetByProductID(p.ID);
            return View(p);
        }
        public ActionResult SaveOption(List<int> countValue, List<string> optionName, List<string> optionValue, int pID)
        {
            var p = _ProductService.GetById(pID);
            _ProductOptionService.RemoveAllOption(p.ID);
            int index = 0;
            for (int i = 0; i < countValue.Count; i++)
            {
                if (optionName[i].Length > 0)
                {
                    string oV = "";
                    for (int j = index; j < index + countValue[i]; j++)
                    {
                        if (optionValue[j] != null && optionValue[j].Length > 0)
                        {
                            oV += optionValue[j] + ";";
                        }
                    }
                    index = index + countValue[i];
                    if (oV.Length > 0)
                    {
                        var po = new ProductOption()
                        {
                            ModifiedDate = DateTime.Now,
                            CreatedDate = DateTime.Now,
                            ProductID = p.ID,
                            UserCreate = null,
                            OptionName = optionName[i],
                            OptionValue = oV
                        };
                        _ProductOptionService.Add(po);
                    }
                }
            }
            TempData["mess"] = "Success";
            return RedirectToAction("Option", "Product", new { id = pID });
        }
    }
}
